package org.cresource.user.service.impl;



import org.cresource.basic.constant.VerifyCodeContants;
import org.cresource.basic.exception.BusinessException;
import org.cresource.basic.util.StrUtils;
import org.cresource.user.domain.User;
import org.cresource.user.mapper.UserMapper;
import org.cresource.user.service.IVerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码 s层
 */
@Service
public class VerifyCodeImpl implements IVerifyCode {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 通过电话获取验证码
     */
    @Override
    public void sendSmsCode(Map<String,String> para){
        String phone = para.get("phone");
        String type = para.get("type");
        //空校验
        if (!StringUtils.hasLength(phone)&&
            !StringUtils.hasLength(type)
                ){
            throw   new BusinessException("未输入电话号码");
        }
        String businessKey="";
        //通过type判断业务
        if("register".equals(type)){
            //通过电话查询用户 判断是否注册
            User user = userMapper.loadUserByPhone(phone);
            if (user!=null){
                throw   new BusinessException("用户已经注册");
            }
            businessKey=VerifyCodeContants.USER_VERFIY_CODE+":"+phone;

        }else if ("binder".equals(type)){
            businessKey=VerifyCodeContants.USER_BINDING_CODE+":"+phone;

        }
        sendSmsCode(businessKey);








    }


    public void sendSmsCode(String businessKey){
        //查询验证码是否存在
        Object mm = redisTemplate.opsForValue().get(businessKey);
        //创建对象装code的值
        String code = "";
        if (mm!=null){
            //转换为string
            String mm2=(String)mm;
            //查询时间戳
            String[] split = mm2.split(":");
            String timeStr = split[1];
            //用当前时间算出验证码发送的时间
            long intervalTime = System.currentTimeMillis() - Long.valueOf(timeStr);
            //未超过一分钟报错
            if (intervalTime<=1*60*1000){
                throw  new BusinessException("请勿在等待时间请求");
                //超过一分钟 得到验证码
            }else {
                code=split[0];
            }

        }else {
            // redis里没有 创建新的验证码 赋值给code
            code = StrUtils.getComplexRandomString(4);
        }
        //redis数据库存值
        redisTemplate.opsForValue().set(businessKey,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
        //短信
        System.out.println("您的验证码为："+code+",请在3分钟之内使用！");
    }


}
